package com.geniusk.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class VideoUtil {

    /**
     * 将视频文件帧处理并以“jpg”格式进行存储
     * 依赖FrameToBufferedImage方法：将frame转换为bufferedImage对象
     * @param path 待截取帧视频路径
     * @return 截取帧字节流
     */
    public static byte[] getVideoFirstFrame(String path) {

        try {
            /*
            获取视频文件
            */
            URL url =new URL(path);
            //利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream inputStream= conn.getInputStream();
            FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(inputStream);
            fFmpegFrameGrabber.start();
            //视频旋转角度，可能是null
            fFmpegFrameGrabber.getVideoMetadata("rotate");
            // 获取视频总帧数
            int ftp = fFmpegFrameGrabber.getLengthInFrames();
            log.info("视频时长{}",ftp / fFmpegFrameGrabber.getFrameRate() / 60);
            // 标识
            int flag = 0;
            while (flag <= ftp) {
                // Frame对象
                Frame frame = fFmpegFrameGrabber.grabImage();
                // 对视频的第五帧进行处理
                if (frame != null && flag == 1) {
                    BufferedImage  bufferedImage= FrameToBufferedImage(frame);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "jpg", out);
                    byte[] b = out.toByteArray();
                    fFmpegFrameGrabber.stop();
                    fFmpegFrameGrabber.close();
                    return b;
                }
                flag++;
            }

        } catch (Exception E) {
            E.printStackTrace();
        }
        return null;
    }

    private static BufferedImage FrameToBufferedImage(Frame frame) {
        // 创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        return converter.getBufferedImage(frame);
    }
}
